package com.koron.css2.meterService.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.MeterBoreBean;
import com.koron.css2.baseConfig.bean.MeterFactoryBean;
import com.koron.css2.baseConfig.bean.MeterModelBean;
import com.koron.css2.baseConfig.mapper.MeterBoreMapper;
import com.koron.css2.baseConfig.mapper.MeterFactoryMapper;
import com.koron.css2.baseConfig.mapper.MeterModelMapper;
import com.koron.css2.meterService.bean.query.MsInfoQueryBean;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsChgPlanDetailMapper;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DictionaryMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.vo.DictionaryVO;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
*  表计管理列表查询（单独接口）
* */
public class MsInfoListOpt implements ServerInterface {
    private static Logger logger = LogManager.getLogger(MsInfoList.class);

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

        @SuppressWarnings("rawtypes")
        MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", PageInfo.class);

        try {
            MsInfoQueryBean bean = JsonUtils.objectToPojo(req.getData(), MsInfoQueryBean.class);
            MsInfoMapper mapper = factory.getMapper(MsInfoMapper.class);
            if(bean.getIsMsChg() != null && bean.getIsMsChg() == 1) {
                //仅针对换表查询在库水表列表
                MsChgPlanDetailMapper msChgPlanDetailMapper = factory.getMapper(MsChgPlanDetailMapper.class);
                List<String> newMeterNos = msChgPlanDetailMapper.selectNewMeterAndProceddNotEnd();
                bean.setNewMeterNos(newMeterNos);
            }

            //水表型号
            MeterModelMapper meterModelMapper = factory.getMapper(MeterModelMapper.class);
            List<MeterModelBean> meterModelBeans = meterModelMapper.getAll();
            Map<String, String> modelNameMap = meterModelBeans.stream().collect(Collectors.toMap(MeterModelBean::getId, MeterModelBean::getModelName));

            PageHelper.startPage(bean.getPage(), bean.getPageCount());
            List<MsInfoDto> list = mapper.selectMsInfoListOpt(bean);

            DictionaryMapper dictionaryMapper = factory.getMapper(DictionaryMapper.class);

            String [] str={"MMS","MMF","TXS","TPW","MMT","MMP"};
            List<DictionaryVO> dictionaryByCodes = dictionaryMapper.findDictionaryByCodes(str);
            Map<String, List<DictionaryVO>> collect = dictionaryByCodes.stream().collect(Collectors.groupingBy(DictionaryVO::getCode));

            Map<String, String> meterStatus = mapDicByCode( collect,"MMS");
            Map<String, String> meterForms = mapDicByCode(collect, "MMF");
            Map<String, String> commOperators = mapDicByCode(collect, "TXS");
            Map<String, String> transmittalModel =mapDicByCode(collect, "TPW");
            Map<String, String> meterTypes = mapDicByCode(collect, "MMT");
            Map<String, String> meterPatterns = mapDicByCode(collect, "MMP");

            list.forEach(t -> {setMsInfo(factory, t,userInfo,meterStatus,meterForms,commOperators,transmittalModel,meterTypes,meterPatterns, modelNameMap);});

            info.setData(new PageInfo<MsInfoDto>(list));

        } catch (Exception e) {
            info.setCode(Constant.MESSAGE_INT_FAIL);
            info.setDescription("查询失败");
            logger.error(e.getMessage(), e);
        }
        return info;
    }
    public static Map<String, String> mapDicByCode(Map<String, List<DictionaryVO>> collect,String code) {
        List<DictionaryVO> dictionarys = collect.get(code);
        return dictionarys.stream().collect(Collectors.toMap(DictionaryVO::getValue, DictionaryVO::getName));
    }

    public List<String> ListIntegration(List<String> ...lists){
        return Arrays.stream(lists).flatMap(List::stream).collect(Collectors.toList());
    }


    public MsInfoDto setMsInfo(SessionFactory factory, MsInfoDto t, UserInfoBean userInfo, Map<String, String> meterStatus, Map<String, String> meterForms, Map<String, String> commOperators, Map<String, String> transmittalModel, Map<String, String> meterTypes, Map<String, String> meterPatterns, Map<String, String> modelNameMap) {

        MeterBoreMapper meterBoreMapper = factory.getMapper(MeterBoreMapper.class);
        if(StringUtils.isNotBlank(t.getMeterBore())) {
            MeterBoreBean boreBean =  meterBoreMapper.selectMeterBoreById(t.getMeterBore());
            // 水表口径
            t.setMeterBoreName(boreBean == null ?t.getMeterBore() :boreBean.getBoreName());
        }
        //传输方式
        if (StringUtils.isNotBlank(t.getTransmittalModel())) {
            t.setTransmittalModelName(transmittalModel.get(t.getTransmittalModel()));
        }
        if (StringUtils.isNotBlank(t.getMeterStatus())) {
            // 水表状态
            t.setMeterStatusName(meterStatus.get(t.getMeterStatus()));
        }
        if (StringUtils.isNotBlank(t.getMeterForm())) {
            // 水表形态
            t.setMeterFormName(meterForms.get(t.getMeterForm()));
        }
        if (StringUtils.isNotBlank(t.getMeterType())) {
            // 水表类型
            t.setMeterTypeName(meterTypes.get(t.getMeterType()));
        }
        if (StringUtils.isNotBlank(t.getCommOperator())) {
            // 通讯商
            t.setCommOperatorName(commOperators.get(t.getCommOperator()));
        }
        if (StringUtils.isNotBlank(t.getMeterPattern())) {
            // 水表型式
            t.setMeterPatternName(meterPatterns.get(t.getMeterPattern()));
        }

        if(t.getValveControl() != null) {
            if(1 == t.getValveControl())
                t.setValveControlName("是");
            if(0 == t.getValveControl())
                t.setValveControlName("否");
        }

        //水表厂商
        MeterFactoryMapper meterFactoryMapper=factory.getMapper(MeterFactoryMapper.class);
        MeterFactoryBean factoryBean =  meterFactoryMapper.selectMeterFactoryById(t.getMeterFactory());
        // 水表厂家
        t.setMeterFactoryName(factoryBean==null?t.getMeterFactory():factoryBean.getFactoryName());
        //水表型号
//		MeterModelMapper mapper = factory.getMapper(MeterModelMapper.class);
//		MeterModelBean modelBean = mapper.selectMeterModelById(t.getMeterModel());
//		t.setMeterModelName(modelBean ==null?t.getMeterModel():modelBean.getModelName());
        String meterModelName = modelNameMap.get(t.getMeterModel());
        if (StringUtils.isNotEmpty(meterModelName)){
            t.setMeterModelName(meterModelName);
        } else {
            t.setMeterModelName(t.getMeterModel());
        }



        return t;
    }
}
